
import pika
import time
import requests

now = time.time()


class MyQueue:
    def __init__(self) -> None:
        credentials = pika.PlainCredentials("guest", "guest")
        # 创建连接
        self.connection = pika.BlockingConnection(pika.ConnectionParameters('127.0.0.1', credentials=credentials))
        # 创建信道
        self.channel = self.connection.channel()

    def sendmes(self, mqueue, mes):
        # 创建队列，或声明已有队列
        self.channel.queue_declare(queue=mqueue)
        # 发布消息
        self.channel.basic_publish(exchange='', routing_key=mqueue, body=mes)

        # 开户接收

    def recivemes(self, myqueue):
        self.channel.queue_declare(queue=myqueue)

        def callback(ch, method, properties, body):
            print("消费者接受到了任务: %r" % body)
            time.sleep(5)
            # 执行业务
            data = eval(body)
            res = requests.get("http://localhost:5000/updateopen?state="+str(data['res'])+"&name="+data['name'])
            code =eval( res.text)
            print(code)
            if code['code']!='200':
                # 失败消息加入队列
                data = eval(body)
                if data['count'] == 3:
                    return 'no'
                else:
                    data['count'] = data['count'] + 1
                self.sendmes(myqueue, str(data))

        self.channel.basic_consume(queue=myqueue, on_message_callback=callback, auto_ack=True)
        self.channel.start_consuming()


myqueue = MyQueue()

# myqueue.sendmes('openbank',str(now))
# myqueue.recivemes('openbank')